package api

import (
	"net/http"

	"gitee.com/hexug/devcloud/mcenter/apps/token"
	"gitee.com/hexug/devcloud/mcenter/common/logger"
	"github.com/emicklei/go-restful/v3"
)

// http://127.0.0.1:2345/mcenter/api/v1/tokens
func (a *ApiServer) IssueToken(request *restful.Request, response *restful.Response) {
	itr := token.NewIssueTokenRequestByPasswordApi()
	if err := request.ReadEntity(itr); err != nil {
		logger.L().Error(err.Error())
		response.WriteErrorString(http.StatusBadRequest, err.Error())
		return
	}
	// fmt.Println(itr)
	tk, err := a.svc.IssueToken(request.Request.Context(), itr)
	if err != nil {
		logger.L().Error(err.Error())
		response.WriteErrorString(http.StatusBadRequest, err.Error())
		return
	}
	response.WriteEntity(tk)
}

// http://127.0.0.1:2345/mcenter/api/v1/tokens/{username}
func (a *ApiServer) ValidateToken(request *restful.Request, response *restful.Response) {
	username := request.PathParameter("username")
	if username == "" {
		response.WriteErrorString(http.StatusBadRequest, "参数不足")
		return
	}
	vtr := token.NewValidateTokenRequest(username)
	if err := request.ReadEntity(vtr); err != nil {
		logger.L().Error(err.Error())
		response.WriteErrorString(http.StatusBadRequest, err.Error())
		return
	}
	tk, err := a.svc.ValidateToken(request.Request.Context(), vtr)
	if err != nil {
		logger.L().Error(err.Error())
		response.WriteErrorString(http.StatusNotFound, err.Error())
		return
	}
	response.WriteEntity(tk)
}

// http://127.0.0.1:2345/mcenter/api/v1/tokens
func (a *ApiServer) DeleteToken(request *restful.Request, response *restful.Response) {
	dtr := token.NewDeleteTokenRequest()
	if err := request.ReadEntity(dtr); err != nil {
		logger.L().Error(err.Error())
		response.WriteErrorString(http.StatusBadRequest, err.Error())
		return
	}
	tk, err := a.svc.DeleteToken(request.Request.Context(), dtr)
	if err != nil {
		logger.L().Error(err.Error())
		response.WriteErrorString(http.StatusNotFound, err.Error())
		return
	}
	response.WriteEntity(tk)
}
